Protected members in mootools classes
You can also be interested in:
Some times ago I wrote about the private static and instance members in mootools classes. Now it's time to speak about the protected members in mootools classes.
So the goal here is to obtain some members which are inherited from the parent class and accessible to a child class but not outside.
The trick is to use the Object.merge function to merge together the private properties of the parent exposed to the children through a protected method and the private properties of the child. Look at the following code:
-
var ids = 1;
-
-
var myParentClass = (function(){
-
-
var _protected_prop = {};
-
-
return new Class({
-
-
initialize: function(id, par1, par2) {
-
this.id = id;
-
_protected_prop[this.id] = {};
-
_protected_prop[this.id].prop1 = 'myvalue1';
-
_protected_prop[this.id].prop2 = true;
-
_protected_prop[this.id].prop3 = 65;
-
},
-
protectedProp: function() {
-
return _protected_prop[this.id];
-
}.protect()
-
});
-
}());
-
-
var myChildClass = (function() {
-
-
var _protected_prop = {};
-
-
return new Class({
-
Extends: myParentClass,
-
initialize: function(par1, par2, par3) {
-
var id = ids++;
-
this.parent(id, par1, par2);
-
// here the protected prop of the parent are ready
-
_protected_prop[this.id] = {
-
prop4: 'myvalue4',
-
prop2: false
-
};
-
_protected_prop[this.id] = Object.merge(this.protectedProp(), _protected_prop[this.id]);
-
}
-
});
-
}());
So what does it happen here?
The
_proptected_prop
of the parent class is a private member but exposed to the children thanks to the protect mootools method (line 18). The a child has it's own private object
_protected_prop
and creates the protected member by merging together its one and the parent one.
The
Object.merge
function alters and returns the parent
protected_prop
object so that really the child has a refeernce to the altereted parent object. Such thing is imporant as it assures that a change to a protected property through a parent method results in a change of the child proetcted property!
Look at the following jsfiddle snippet, it shows what explained above. (follow this link if you can't see it.
Your Smartwatch Loves Tasker!
Your Smartwatch Loves Tasker!
Featured
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May